package com.good.service.realm;

import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.good.entity.Admin;
import com.good.entity.Role;
import com.good.service.AdminService;

public class ShiroDbRealm extends AuthorizingRealm {
	@Resource(name = "adminServiceImpl")
	private AdminService adminService;

	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		/**
		 * @author ieei 授权
		 */

		String userName = (String) principals.fromRealm(getName()).iterator()
				.next();
		Admin user = adminService.getByAccount(userName);
		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			Set<Role> roles = user.getRoles();
			if(roles!=null&&roles.size()>0){
				for (Role role : roles) {
					info.addRole(role.getName());
					info.addStringPermissions(role.getAuthorities());
				}
			}

			return info;
		} else {
			return null;
		}
	}

	/**
	 * 登录后回调
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		System.out.println("登录后的回调函数doGetAuthenticationInfo");
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		Admin admin = adminService.getByAccount(token.getUsername());
		if (admin != null) {
			System.out.println("getName"+getName());
			return new SimpleAuthenticationInfo(admin.getAccount(),
					admin.getPassword(), getName());
		} else {
			return null;
		}
	}
}
